// 导入模块
import { useMemberStore } from '@/stores'
import Request, { type HttpMethod, type HttpRequestConfig } from 'luch-request'

// 实例化网络请求
const service = new Request({
  // 接口基地址
  baseURL: 'https://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 50 * 1000,
  custom: {
    loading: true
  }
})

// 接口白名单
// const whiteList = ['/code', '/login', '/login/password']

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    if (config.custom?.loading) {
      uni.showLoading({
        title: '加载中...',
        mask: true
      })
    }
    // 统一处理请求头,从pinia中携带token
    const memberStore = useMemberStore()
    if (memberStore.profile?.token && config.header) {
      config.header.Authorization = memberStore.profile.token
    }

    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)
// 响应拦截器
service.interceptors.response.use(
  (res) => {
    uni.hideLoading()
    // 统一处理错误
    // if (res.data.code !== 10000) {
    //   uni.showToast({
    //     title: res.data.message,
    //     icon: 'none',
    //   })
    //   return Promise.reject(res.data)
    // }
    return res.data
  },
  (error) => {
    uni.hideLoading()
    // 统一处理token失效

    return Promise.reject(error)
  }
)

interface ServiceResponse<T> {
  code: string
  message: string
  result: T
}

// 封装请求工具
const request = <T>(
  url: string,
  method: HttpMethod = 'GET',
  submitData?: object,
  config?: HttpRequestConfig
) => {
  return service.request<T, ServiceResponse<T>>({
    url: url,
    method: method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: submitData,
    ...config
  })
}

// 导出配置好的模网络模块
export { service, request }
